package cn.edu.zut.soft.graduate.massageCenter.bo;

import cn.edu.zut.soft.basic.core.model.bo.CommonResult;
import cn.edu.zut.soft.basic.core.model.dao.Criteria;
import cn.edu.zut.soft.graduate.base.bo.BasicBOImpl;
import cn.edu.zut.soft.graduate.base.dao.BasicDAO;
import cn.edu.zut.soft.graduate.core.constant.Role;
import cn.edu.zut.soft.graduate.core.model.Impl.Notice;
import cn.edu.zut.soft.graduate.core.query.NoticeQuery;
import cn.edu.zut.soft.graduate.core.vo.Owner;
import cn.edu.zut.soft.graduate.massageCenter.dao.NoticeDAO;
import com.alibaba.fastjson.JSON;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;

/**
 * Created by chuchuang on 16/10/29.
 */
@Repository
public class NoticeBOImpl extends BasicBOImpl<Notice, NoticeQuery> implements NoticeBO {

    @Resource
    private NoticeDAO<Notice> noticeDAO;

    @Override
    protected BasicDAO<Integer, Notice> getDAO() {
        return noticeDAO;
    }


    @Override
    public Notice get(Integer id) {
        noticeDAO.addRead(id);
        return super.get(id);
    }

    @Override
    protected List<Criteria> Query(NoticeQuery noticeQuery) {
        Criteria criteria = new Criteria();
        if (noticeQuery.getTitle() != null && !"".equals(noticeQuery.getTitle().trim())) {
            criteria.andLike("title", noticeQuery.getTitle() + "%");
        }
        if (noticeQuery.getRole() != null) {
            if (!"all".equals(noticeQuery.getRole().trim())) {
                criteria.andRegexp("role", noticeQuery.getRole() + "?");
            }

        }
        return Collections.singletonList(criteria);
    }

    @Override
    public CommonResult<Notice> save(Notice notice, Owner owner, List<Role> roleList, String operator) {
        Assert.notNull(owner, "归属人不能为空");
        if (roleList.isEmpty()) {
            roleList.add(Role.tea);
            roleList.add(Role.stu);
        }
        notice.setOwner(JSON.toJSONString(owner));
        notice.setRole(JSON.toJSONString(roleList));
        return super.save(notice, operator);
    }

    @Override
    public CommonResult<Notice> update(Notice notice, Owner owner, List<Role> roleList, String operator) {
        Assert.notNull(owner, "归属人不能为空");
        if (roleList.isEmpty()) {
            roleList.add(Role.tea);
            roleList.add(Role.stu);
        }
        notice.setOwner(JSON.toJSONString(owner));
        notice.setRole(JSON.toJSONString(roleList));
        return super.update(notice, operator);
    }


}
